C# 動態生成物件與其他物件綁定


我的使用情境是點擊動態生成的圖片會做出相應動作
但是這個動作必須與他一起生成的Label等其他物件有關連
所以可以使用以下方法

打包成一個自訂的元件
並將元件與生成的圖片做關聯

var pictureBoxLabelPair = new Tuple<PictureBox, Label>(pictureBox, label);
pictureBox.Tag = pictureBoxLabelPair;

之後在處理事件的地方將關聯的物件存取到新的物件
這樣就可以拿取或控制想要的物件了

PictureBox clickedPictureBox = (PictureBox)sender;
var pictureBoxLabelPair = (Tuple<PictureBox, Label>)clickedPictureBox.Tag;
Label label = pictureBoxLabelPair.Item2;

第二種方式就是用class

class MyData
{
    public int IntValue { get; set; }
    public string StringValue { get; set; }
    public bool BoolValue { get; set; }
    public double DoubleValue { get; set; }
}
var data = new MyData
{
    IntValue = 42,
    StringValue = "Hello, World!",
    BoolValue = true,
    DoubleValue = 3.14
};
var pictureBoxLabelPair = (MyData)clickedPictureBox.Tag;
#C# #Winform







你可能感興趣的文章

Array Cardio Day 1

Array Cardio Day 1

MTR04_0920

MTR04_0920

[筆記] React 隨手記 (React 抽獎機率設定)

[筆記] React 隨手記 (React 抽獎機率設定)






留言討論